# -*- coding: utf-8 -*-
"""购物车页面对象 (`df_cart/cart.html`)"""

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

from .base import BasePage
from common.log import log


class CartPage(BasePage):
    # ------- 通用定位 ---------
    CART_ROWS = (By.CSS_SELECTOR, "ul.cart_list_td")
    CHECK_ALL = (By.ID, "check_all")
    TOTAL_TEXT = (By.ID, "total")

    def rows(self):
        return self.driver.find_elements(*self.CART_ROWS)

    # ------- 针对单行商品操作 ---------
    def _ops_in_row(self, row_el):
        plus = row_el.find_element(By.CSS_SELECTOR, "a.add")
        minus = row_el.find_element(By.CSS_SELECTOR, "a.minus")
        input_box = row_el.find_element(By.CSS_SELECTOR, "input.num_show")
        delete_link = row_el.find_element(By.CSS_SELECTOR, "li.col08 a")
        return plus, minus, input_box, delete_link

    def increase(self, row_el):
        plus, *_ = self._ops_in_row(row_el)
        plus.click()

    def decrease(self, row_el):
        _, minus, *_ = self._ops_in_row(row_el)
        minus.click()

    def set_quantity(self, row_el, count: int):
        _, _, input_box, _ = self._ops_in_row(row_el)
        input_box.clear()
        input_box.send_keys(str(count))
        # 触发 blur
        row_el.click()

    def quantity(self, row_el):
        _, _, input_box, _ = self._ops_in_row(row_el)
        return int(input_box.get_attribute("value"))

    def delete_row(self, row_el):
        *_, delete_link = self._ops_in_row(row_el)
        delete_link.click()

        # 处理前端 confirm("确定删除") 弹窗，用户操作为“确定”
        from selenium.common.exceptions import NoAlertPresentException

        try:
            alert = self.driver.switch_to.alert
            log.debug(f"确认删除弹窗: {alert.text}")
            alert.accept()
        except NoAlertPresentException:
            # 某些情况下（JS 失效或页面变动）可能没有弹窗，直接忽略
            pass

        # 弹窗处理完毕后，等待该行元素被移除
        WebDriverWait(self.driver, 5).until(EC.staleness_of(row_el)) 